<template>
  <el-dialog
    v-model="dialogVisible"
    title="二次认证"
    width="460px"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    :show-close="true"
    @close="handleClose"
  >
    <div class="secondary-auth-content">
      <el-result
        icon="warning"
        title="需要二次认证"
        sub-title="请使用微信扫描下方二维码完成身份验证"
      >
        <template #extra>
          <div class="qr-container">
            <iframe
              :src="qrCodeUrl"
              frameborder="0"
              scrolling="no"
              class="qr-iframe"
              name="oauth-iframe"
            />
          </div>
        </template>
      </el-result>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from "vue";
import { ElMessage, ElDialog, ElResult } from "element-plus";
import { useRouter } from "vue-router";
import { removeAuthLimit } from "@/api";

const props = withDefaults(
  defineProps<{
    visible: boolean;
  }>(),
  {
    visible: false
  }
);

const emit = defineEmits<{
  (e: "update:visible", value: boolean): void;
  (e: "auth-success"): void;
  (e: "cancel"): void;
}>();

const router = useRouter();
const qrCodeUrl = ref("");
const dialogVisible = ref(props.visible);

// 处理弹窗关闭
const handleClose = () => {
  dialogVisible.value = false;
  emit("cancel");
  ElMessage.warning("已取消二次鉴权，操作未执行");
};

// 监听visible属性变化
watch(
  () => props.visible,
  newVal => {
    dialogVisible.value = newVal;
  }
);

// 监听对话框状态变化
watch(
  () => dialogVisible.value,
  newVal => {
    emit("update:visible", newVal);
  }
);

// 处理认证成功
const handleAuthSuccess = async (code: string) => {
  try {
    // 调用解除限制接口
    const res = await removeAuthLimit(code);
    if (res.status === "success") {
      dialogVisible.value = false;
      emit("auth-success");
      ElMessage.success(res.msg || "解除限制成功！");
      // 延迟一下再刷新页面，让用户看到成功提示
      setTimeout(() => {
        window.location.reload();
      }, 1000);
    } else {
      ElMessage.error(res.msg || "认证失败");
    }
  } catch (error) {
    console.error("解除限制失败:", error);
    ElMessage.error("认证失败");
  }
};

// 检查URL中的code参数
const checkUrlCode = () => {
  try {
    // 获取完整的hash部分（包括查询参数）
    const fullHash = window.location.hash;

    // 使用正则表达式匹配code参数
    const codeMatch = fullHash.match(/code=([^&]+)/);
    if (codeMatch && codeMatch[1]) {
      const code = codeMatch[1];
      handleAuthSuccess(code);
    }
  } catch (error) {
    console.error("处理code参数失败:", error);
  }
};

// 获取二维码
const getQRCode = () => {
  try {
    const APPID = "ndd956a392c8b55d39";
    // 将回调地址指向当前页面，并添加target参数
    const currentUrl = encodeURIComponent(window.location.href);

    qrCodeUrl.value = `https://oauth.henau.edu.cn/oauth2_qr_connect/login?appid=${APPID}&redirect_uri=${currentUrl}&response_type=code&scope=henauapi_login&target=oauth-iframe`;
  } catch (error) {
    console.error("获取二维码失败:", error);
  }
};

// 监听hash变化
const handleHashChange = () => {
  checkUrlCode();
};

// 处理OAuth回调消息
const handleOAuthMessage = (event: MessageEvent) => {
  try {
    // 验证消息来源
    if (event.origin !== "https://oauth.henau.edu.cn") return;

    const data = event.data;
    // 处理iframe内部的认证成功消息
    if (data.type === "oauth_success" && data.code) {
      handleAuthSuccess(data.code);
      return;
    }

    // 处理重定向回来的认证成功消息
    if (typeof data === "string") {
      // 处理特殊格式的URL: /user/index?target=oauth-iframe?code=xxx
      const codeMatch = data.match(/code=([^&]+)/);
      if (codeMatch && codeMatch[1]) {
        handleAuthSuccess(codeMatch[1]);
      }
      return;
    }
  } catch (error) {
    console.error("处理OAuth消息失败:", error);
  }
};

onMounted(() => {
  getQRCode();
  // 添加hash变化监听
  window.addEventListener("hashchange", handleHashChange);
  // 检查URL中的code参数
  checkUrlCode();
});

onUnmounted(() => {
  // 移除hash变化监听
  window.removeEventListener("hashchange", handleHashChange);
});
</script>

<style lang="scss" scoped>
.secondary-auth-content {
  :deep(.el-result) {
    padding: 0;
  }

  :deep(.el-result__icon) {
    margin-bottom: 12px;
  }

  :deep(.el-result__title) {
    margin-top: 0;
    margin-bottom: 8px;
    font-size: 20px;
  }

  :deep(.el-result__subtitle) {
    margin-top: 0;
    margin-bottom: 16px;
    font-size: 14px;
  }

  .qr-container {
    width: 320px;
    height: 300px;
    margin: 0 auto;
    overflow: hidden;

    .qr-iframe {
      width: 100%;
      height: 100%;
      transform: scale(1.15);
      transform-origin: center center;
    }
  }
}

:deep(.el-dialog__header) {
  padding-bottom: 12px;
  margin-right: 0;
  text-align: center;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style>
